/*********************************
 * jsmud: JavaScript MUD Kernel  *
 *          Mojodo, Inc.         *
 *        Sean Middleditch       *
 * Copyright (C) 2005,2007,2008  *
 *      All rights reserved.     *
 *   See COPYING for licensing.  *
 *********************************/

/* ==== SYSTEM INCLUDES ==== */

#include <string.h>
#include <limits.h>

/* ==== LIBRARY INCLUDES ==== */

#include <sqlite3.h>
#include <zlib.h>

#define XP_UNIX 1
#define MOZILLA_1_8_BRANCH 1
#include <jsapi.h>
#undef XP_UNIX
#undef MOZILLA_1_8_BRANCH

/* ==== JSMUD HEADER ==== */

#include "jsmud.h"

/* ==== FUNCTIONS ==== */

const char* makepath (const char* path)
{
	static char buffer[PATH_MAX];
	const char* const end = buffer + sizeof(buffer);
	const char* iptr;
	char* start;
	char* optr;
	char* sep;
	int len;

	/* initialize buffer with lib path and set the start pointer.
	 * we don't handle truncation in a friendly way, but we do
	 * handle it.  we just make sure to have at least 2 free bytes,
	 * for the strcpy at the end of this routine. */
	len = snprintf(buffer, sizeof(buffer), "%s", opt_data_path);
	start = buffer + len;
	if (start >= end)
		return buffer;

	for (optr = start, iptr = path; *iptr != 0; iptr += len) {
		/* skip separators with no preceding component */
		while (*iptr == '/')
			++iptr;

		/* find separator */
		sep = strchr(iptr, '/');
		len = sep ? sep-iptr : strlen(iptr);

		/* self pointer (e.g. .) */
		if (len == 1 && strncmp(iptr, ".", 1) == 0) {
			/* ignore */
		/* parent pointer (e.g. ..) */
		} else if (len == 2 && strncmp(iptr, "..", 2) == 0) {
			/* if we're not sitting at the top of the buffer, jump our
			 * output pointer back to the last /, which is guaranteed
			 * exist in a non-empty buffer */
			if (optr != buffer) {
				optr = strrchr(start, '/');
				if (optr == NULL)
					optr = start;
				*optr = 0;
			}
		/* regular component */
		} else if (len > 0) {
			/* note that we silently ignore truncations; overflows
			 * will not happen, we'll exit the loop on truncation */
			optr += snprintf(optr, end-optr, "/%.*s", len, iptr);
			if (optr >= end)
				break;
		}
	}

	return buffer;
}

/* vim: set tabstop=2 shiftwidth=2 ai: */
